package com.lyons.easyweb.listener;

import java.util.List;

import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lyons.easyweb.modular.timer.pojo.Timers;
import com.lyons.easyweb.modular.timer.service.TimerExeService;
import com.lyons.easyweb.modular.timer.service.TimersService;

import cn.hutool.cron.CronUtil;
import cn.hutool.extra.spring.SpringUtil;

/**
 * 项目定时任务启动的listener
 */
@Component
public class TimerTaskRunListener implements ApplicationListener<ApplicationStartedEvent>, Ordered {

	@Override
	public void onApplicationEvent(ApplicationStartedEvent event) {
		
		TimersService timersService = SpringUtil.getBean(TimersService.class);
		TimerExeService timerExeService = SpringUtil.getBean(TimerExeService.class);

		// 获取所有开启状态的任务
		List<Timers> list = timersService.list(new LambdaQueryWrapper<Timers>().eq(Timers::getJobStatus, 1));

		// 添加定时任务到调度器
		for (Timers timer : list) {
			timerExeService.startTimer(String.valueOf(timer.getId()), timer.getCron(), timer.getActionClass());
		}

		// 设置秒级别的启用
		CronUtil.setMatchSecond(true);

		// 启动定时器执行器
		CronUtil.start();
	}

	@Override
	public int getOrder() {
		return LOWEST_PRECEDENCE;
	}
	
}
